const router = require('koa-router')()
const util = require('./../utils/util')
const Menu = require('./../modules/MenusSchema')
router.prefix('/menu')

router.get('/list', async (ctx) => {
  let { menuName, menuState } = ctx.request.query
  const params = {}
  if (menuName) params.menuName = menuName
  if (menuState) params.menuState = menuState
  let rootList = (await Menu.find(params)) || []
  const data = util.getTreeMenu(rootList, null, [])
  ctx.body = util.success(data, '查询成功')
})

router.post('/operate', async (ctx) => {
  const { _id, action, ...params } = ctx.request.body
  let res, info
  try {
    if (action == 'add') {
      res = await Menu.create(params)
      info = '创建成功'
    } else if (action == 'edit') {
      res = await Menu.findByIdAndUpdate(_id, params)
      info = '更新成功'
    } else if (action == 'delete') {
      res = await Menu.findByIdAndRemove(_id)
      //从集合中删除所有匹配到父级ID的文档
      await Menu.deleteMany({ parentId: { $all: [_id] } })
      info = '删除成功'
    } else {
      util.fail('非法请求,已记录后台!请立即停止!', util.CODE.PARAM_ERROR)
    }
    ctx.body = util.success('ok', info)
  } catch (error) {
    util.fail(error.stack)
  }
})

module.exports = router
